//
//  SHHModifyUserInfoVC.swift
//  GoTravel
//
//  Created by lanou3g on 16/3/7.
//  Copyright © 2016年 SHH. All rights reserved.
//

import UIKit

class SHHModifyUserInfoVC: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate,MBProgressHUDDelegate {

    
    let nameLabe = UILabel()
    let genderLabel = UILabel()
    let nameText = UITextField()
    let genderText = UITextField()
    var genderButton = UIButton()
    //头视图
    let headImg = UIImageView()
    
    //全局变量的高度和宽度的定义
    let kWidth = UIScreen.mainScreen().bounds.width
    let kHeight = UIScreen.mainScreen().bounds.width
    let kBackH = UIScreen.mainScreen().bounds.width / 2
    let kLeftGap = UIScreen.mainScreen().bounds.width / 8
    let kGap = UIScreen.mainScreen().bounds.height / 20
    let kHeadWidth = 70
    let kHeadHeight = 70
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.whiteColor()
        self.navigationItem.title = "修改资料"
        
        //设置navigation上的返回按钮
        var normalImg = UIImage(named: "iconfont-iconfanhui-2")
        normalImg = normalImg?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: normalImg, style: UIBarButtonItemStyle.Plain, target: self, action: Selector("leftAction:"))
        //设置navigation上的确认按钮
        var OkIma = UIImage(named: "iconfont-queren")
        OkIma = OkIma?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: OkIma, style: UIBarButtonItemStyle.Plain, target: self, action: Selector("rightAction:"))
        
        //页面布局的设计
        self.drawView()
        
    }
    
    //点击navigation按钮上的事件
    func leftAction(sender:UIBarButtonItem) {
        self.navigationController?.popToRootViewControllerAnimated(true)
    }
    
    //点击保存按钮的事件
    func rightAction(sender:UIBarButtonItem) {
        let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
        hud.delegate = self
        hud.labelText = "正在保存..."
        let user = SHHGetUser.sharedGetUser?.getUserInfo()
        let query = AVQuery(className: "UserInfo")
        query.whereKey("user_id", equalTo: user!.user_id)
        let object = query.findObjects().first
        if self.nameText.text == "" || self.nameText.text == nil {
            
        }else{
            object?.setObject(self.nameText.text, forKey: "name")
        }
        
        if self.genderButton.titleLabel?.text == "男" {
            object?.setObject("男", forKey: "gender")
        }else{
            object?.setObject("女", forKey: "gender")
        }
        
        let data =  UIImagePNGRepresentation(self.headImg.image!)
        let file = AVFile(name: "avatar.png", data: data)
        if file.save() {
            object?.setObject(file.url, forKey: "photo_url")
        }
        object?.saveInBackgroundWithBlock({ (succeeded:Bool, error:NSError!) -> Void in
            
            if succeeded {
                hud.hide(true)
                let user = SHHGetUser.sharedGetUser
                user!.updateUserInfo()
                self.showSuccessAlert()
            }else{
                hud.hide(true)
                self.showFailAlert()
            }
            
        })
        
    }
    
    //实现MBProgressHUD的代理
    func hudWasHidden(var hud: MBProgressHUD!) {
        hud.removeFromSuperview()
        hud = nil
    }
    
    //保存成功
    func showSuccessAlert() {
        let alert = UIAlertController(title: "提示", message: "保存成功", preferredStyle: UIAlertControllerStyle.Alert)
        let defauletAction = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default) { (action:UIAlertAction) -> Void in
            self.navigationController?.popToRootViewControllerAnimated(true)
        }
        alert.addAction(defauletAction)
        self.presentViewController(alert, animated: true, completion: nil)
    }
    
    //保存失败
    func showFailAlert() {
        let alert = UIAlertController(title: "提示", message: "保存失败", preferredStyle: UIAlertControllerStyle.Alert)
        let defauletAction = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default) { (action:UIAlertAction) -> Void in
            
        }
        alert.addAction(defauletAction)
        self.presentViewController(alert, animated: true, completion: nil)
    }
    
    //页面布局按钮的设计
    func drawView() {
        //设置视图
        let headerView = UIImageView(frame: CGRectMake(0,64,kWidth,kBackH))
        headerView.image = UIImage(named: "9.jpg")
        headerView.userInteractionEnabled = true
        
        let userInfo = SHHGetUser.sharedGetUser!.getUserInfo()
        self.headImg.frame = CGRectMake(kWidth / 2.45, kBackH / 4.5, CGFloat(kHeadWidth), CGFloat(kHeadHeight))
        
        if userInfo.photo_url == "" || userInfo.photo_url == nil {
            self.headImg.image = UIImage(named: "iconfont-unie64d")
        }else{
            self.headImg.sd_setImageWithURL(NSURL(string: userInfo.photo_url!), placeholderImage: UIImage(named: "iconfont-unie64d"))
        }
        self.headImg.layer.cornerRadius = 35
        self.headImg.layer.masksToBounds = true
        self.headImg.userInteractionEnabled = true
        headerView.addSubview(self.headImg)
        
        //给图片添加手势
        let tap = UITapGestureRecognizer(target: self, action: Selector("tapAction:"))
        self.headImg.addGestureRecognizer(tap)
        
        self.view.addSubview(headerView)
        
        //用户名的设置
        self.nameLabe.frame = CGRectMake(CGFloat(kGap), CGFloat(kBackH) * 1.3 , CGFloat(5 * kGap) , CGFloat(3 * kGap))
        self.nameLabe.text = "昵称:"
        self.view.addSubview(self.nameLabe)
        
        self.nameText.frame = CGRectMake(CGFloat(2.5 * kGap), CGFloat(1.45 * kBackH), CGFloat(8 * kGap), CGFloat(1.4 * kGap))
        self.nameText.text = userInfo.name
        self.view.addSubview(self.nameText)
        
        //用户性别的设置
        self.genderLabel.frame = CGRectMake(CGFloat(kGap), CGFloat(kBackH) * 1.6 , CGFloat(5 * kGap) , CGFloat(3 * kGap))
        self.genderLabel.text = "性别"
        self.view.addSubview(self.genderLabel)
        
        self.genderButton = UIButton(type: UIButtonType.System)
        self.genderButton.frame = CGRectMake(CGFloat(2.5 * kGap), CGFloat(kBackH) * 1.75, CGFloat(1.5 * kGap), CGFloat(1.4 * kGap))
        self.genderButton.setTitle("我尼玛", forState: UIControlState.Normal)
        if userInfo.gender == "男" {
            self.genderButton.setTitle("男", forState: UIControlState.Normal)
        }else{
            self.genderButton.setTitle("女", forState: UIControlState.Normal)
        }
        self.genderButton.addTarget(self, action: Selector("showSex:"), forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(self.genderButton)
    }

    //图片的点击事件
    func tapAction(sender:UITapGestureRecognizer) {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
        let takePhotoAction = UIAlertAction(title: "照相", style: UIAlertActionStyle.Default) { (action:UIAlertAction) -> Void in
            
            //判断是否可以打开相机，模拟器此功能无法使用
            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
                //调用系统相机
                let picker = UIImagePickerController()
                picker.sourceType = UIImagePickerControllerSourceType.Camera
                picker.delegate = self
                picker.allowsEditing = true
                self.presentViewController(picker, animated: true, completion: nil)
            }else{
                let alert = UIAlertController(title: "Error", message: "你没有摄像头", preferredStyle: UIAlertControllerStyle.Alert)
                let cancelAction = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: nil)
                alert.addAction(cancelAction)
                self.presentViewController(alert, animated: true, completion: nil)
            }
        }
        
        let photoAction = UIAlertAction(title: "从相册中选择", style: UIAlertActionStyle.Default) { (action:UIAlertAction) -> Void in
            //相册是可以用模拟器打开的
            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
                let picker = UIImagePickerController()
                picker.delegate = self
                picker.allowsEditing = true
                picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
                self.presentViewController(picker, animated: true, completion: nil)
            }else{
                let alert = UIAlertController(title: "Error", message: "你没有照片", preferredStyle: UIAlertControllerStyle.Alert)
                let cancelAction = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: nil)
                alert.addAction(cancelAction)
                self.presentViewController(alert, animated: true, completion: nil)
            }
        }
        
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
        alert.addAction(takePhotoAction)
        alert.addAction(photoAction)
        alert.addAction(cancelAction)
        self.presentViewController(alert, animated: true, completion: nil)
    }
    
    //选中图片进入的代理方法
    //拍摄完成后要执行的方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        let image:UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        self.headImg.image = image
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imageCompressForWidth(sourceImage:UIImage,defineWidth:CGFloat)->UIImage {
        let imageSize:CGSize = sourceImage.size
        let width = imageSize.width
        let height = imageSize.height
        let targetWidth = defineWidth
        let targetHeight = (targetWidth / width) / height
        UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight))
        sourceImage.drawInRect(CGRectMake(0, 0, targetWidth, targetHeight))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
    //点击cancel按钮后执行方法
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    //选择性别的点击事件
    func showSex(sender:UIButton) {
        let title = "性别"
        let Lady = "女"
        let Gentleman = "男"
        
        let alert = UIAlertController(title: title, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
        let gentlemanAction = UIAlertAction(title: Gentleman, style: UIAlertActionStyle.Default) { (action:UIAlertAction) -> Void in
            self.genderButton.setTitle(Gentleman, forState: UIControlState.Normal)
        }
        let ladyAction = UIAlertAction(title: Lady, style: UIAlertActionStyle.Default) { (action:UIAlertAction) -> Void in
            self.genderButton.setTitle(Lady, forState: UIControlState.Normal)
        }
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Default, handler: nil)
        alert.addAction(gentlemanAction)
        alert.addAction(ladyAction)
        alert.addAction(cancelAction)
        
        self.presentViewController(alert, animated: true, completion: nil)
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
